<template>
	<div class="video-upload">
		<!-- 标题区域 -->
		<div class="form-group title-section">
			<label for="title" class="title-label"><strong>视频标题</strong></label>
			<input type="text" class="form-control title-input" id="title" v-model="video.title"
				placeholder="请输入视频标题">
		</div>

		<!-- 描述区域 -->
		<div class="form-group description-section">
			<label for="description" class="description-label"><strong>视频描述</strong></label>
			<textarea class="form-control description-input" id="description" v-model="video.description"
				placeholder="请输入视频描述"></textarea>
		</div>

		<!-- 标签选择区域 -->
		<TagSelector v-model="video.tags" label="目标用户标签" />

		<!-- 视频上传区域 -->
		<div class="upload-grid" :class="gridClass">
			<div v-if="video.file" class="upload-item" @click="previewVideo(video.file.url)">
				<video :src="video.file.url" controls class="uploaded-file"></video>
				<button @click.stop="removeVideo" class="remove-button">删除</button>
			</div>
			<!-- 添加视频按钮 -->
			<div v-if="!video.file" class="upload-item add-item" @click="addVideo">
				<i class="fas fa-plus">添加视频</i>
			</div>
		</div>

		<!-- 提交按钮 -->
		<div class="submit-section">
			<button class="btn btn-primary submit-button" @click="submitVideo">提交视频</button>
		</div>
	</div>
</template>

<script>
import TagSelector from '@/components/TagSelector/TagSelector.vue';

export default {
	components: {
		TagSelector
	},
	data() {
		return {
			video: {
				file: null,
				title: '',
				description: '',
				tags: []
			},
			gridClass: 'default-grid-class'
		};
	},
	methods: {
		addVideo() {
			// 使用微信小程序的 API 选择视频
			wx.chooseVideo({
				sourceType: ['album', 'camera'],
				maxDuration: 60,
				success: (res) => {
					this.video.file = {
						url: res.tempFilePath,
						type: 'video/mp4'
					}; // 假设视频类型为 video/mp4
				}
			});
		},
		removeVideo() {
			// 删除视频逻辑
			this.video.file = null;
		},
		previewVideo(url) {
			wx.previewImage({
				current: url, // 当前显示图片的链接
				urls: [url] // 需要预览的图片链接列表
			});
		},
		submitVideo() {
			if (!this.video.file) {
				console.error('请上传视频');
				return;
			}

			// 显示上传中
			uni.showLoading({
				title: '上传中...',
				mask: true,
			});

			// 生成唯一的文件名
			const uniqueName = this.$requests.generateUniqueFileName();
			const fileExtension = this.video.file.url.split('.').pop() || 'mp4';
			const uniqueFileName = `train/video/${uniqueName}.${fileExtension}`;

			this.$requests.uploadFile({
				filePath: this.video.file.url,
				name: uniqueFileName,
				success: (res) => {
                    const ok = (res && typeof res.statusCode === 'number' && res.statusCode >= 200 && res.statusCode < 300)
                        || !!res.fileID
                        || (res && res.data && res.data.file_id);
                    if (ok) {
                        console.log('视频上传成功:', res);
                        const fileId = res.fileID || (res.data && res.data.file_id);
                        this.sendVideoInfo(fileId);
                    } else {
						uni.hideLoading();
                        console.error('上传失败:', res);
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none',
						});
                    }
				},
				fail: (err) => {
					uni.hideLoading();
					console.error("failed to upload", err);
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none',
					});
				},
			});
		},
		sendVideoInfo(fileId) {
			this.$request({
				url: "/train/video/upload/",
				method: "POST",
				data: {
					file_url: fileId,
					title: this.video.title,
					description: this.video.description,
					tags: this.video.tags,
				},
				success: (response) => {
					if (response.statusCode === 200) {
						console.log('视频提交成功:', response);
						uni.hideLoading();
						uni.showToast({
							title: '提交成功',
							icon: 'success',
						});
						// 成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 600);
					} else {
						uni.hideLoading();
						console.error('视频提交失败:', response);
						uni.showToast({
							title: '提交失败，请重试',
							icon: 'none',
						});
					}
				},
				fail: (error) => {
					uni.hideLoading();
					console.error('视频提交失败:', error);
					uni.showToast({
						title: '提交失败，请检查网络',
						icon: 'none',
					});
				},
			});
		}
	}
};
</script>

<style>
	.video-upload {
		max-width: 600px;
		margin: 0 auto;
		padding: 20px;
		border: 1px solid #ccc;
		border-radius: 10px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		background-color: #fff;
	}

	/* 标题区域 */
	.title-section {
		margin-bottom: 25px;
	}

	.title-label {
		font-size: 18px;
		color: #333;
		margin-bottom: 10px;
		display: block;
	}

	.title-input {
		font-size: 16px;
		padding: 12px;
		border: 2px solid #ddd;
		border-radius: 5px;
		transition: border-color 0.3s;
		width: calc(100% - 20px);
		margin-right: 10px;
	}

	.title-input:focus {
		border-color: #007bff;
		outline: none;
	}

	/* 描述区域 */
	.description-section {
		margin-bottom: 25px;
	}

	.description-label {
		font-size: 18px;
		color: #333;
		margin-bottom: 10px;
		display: block;
	}

	.description-input {
		width: calc(100% - 20px);
		font-size: 14px;
		line-height: 1.6;
		border: 1px solid #ddd;
		border-radius: 5px;
		background-color: #f9f9f9;
		resize: none;
		min-height: 150px;
		max-height: 400px;
		overflow-y: auto;
		transition: border-color 0.3s;
		padding: 10px;
		margin-right: 10px;
		box-sizing: content-box;
	}

	.description-input:focus {
		border-color: #007bff;
		outline: none;
	}


	/* 视频上传区域 */
	.upload-grid {
		display: grid;
		grid-template-columns: repeat(3, minmax(100px, 1fr));
		gap: 15px;
		margin-bottom: 25px;
	}

	.upload-item {
		position: relative;
		border: 2px dashed #ddd;
		border-radius: 5px;
		height: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		transition: border-color 0.3s;
	}

	.upload-item:hover {
		border-color: #007bff;
	}

	.upload-item.add-item {
		background-color: #e9ecef;
		color: #555;
		font-size: 20px;
		text-align: center;
	}

	.uploaded-file {
		max-width: 100%;
		max-height: 100%;
		object-fit: cover;
		border-radius: 5px;
	}

	.remove-button {
		position: absolute;
		top: 5px;
		right: 5px;
		background-color: red;
		color: white;
		border: none;
		padding: 5px 10px;
		border-radius: 3px;
		cursor: pointer;
		font-size: 12px;
	}

	/* 提交按钮 */
	.submit-section {
		text-align: center;
	}

	.submit-button {
		padding: 12px 25px;
		font-size: 16px;
		color: #fff;
		background-color: #007bff;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.submit-button:hover {
		background-color: #0056b3;
	}

	/* 响应式布局 */
	@media (max-width: 768px) {
		.video-upload {
			padding: 15px;
		}

		.title-input,
		.description-input {
			font-size: 14px;
		}

		.upload-grid {
			grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
		}

		.submit-button {
			padding: 10px 20px;
			font-size: 14px;
		}
	}
</style>